import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import Cookies from 'js-cookie'
import { roles } from '@/api/common'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: getInfo('nickname'),
    avatar: getInfo('avatar'),
    lastTime: getInfo('lastTime'),
    userId: getInfo('userId'),
    position: getInfo('position'),
    classname: getInfo('classname'),
    isTeacher: getInfo('isTeacher')
  }
}

function saveCookie(key, val) {
  Cookies.set(key, val)
}

function getCookie(key) {
  return Cookies.get(key)
}

function getInfo(key) {
  let info = getCookie('info')
  if (info) {
    const infoJson = JSON.parse(info)
    return infoJson[key]
  }
}

function clearInfo() {
  const info = getCookie('info')
  if (info) {
    Cookies.remove('info')
  }
}
const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLE: (state, role) => {
    state.isTeacher = role
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(async response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        commit('SET_NAME', data.nickname)
        setToken(data.token)
        // 获取权限
        const roleRes = await roles()
        data.isTeacher = roleRes.data
        commit('SET_ROLE', data.isTeacher)
        if (data.isTeacher) {
          commit('SET_AVATAR', require('@/assets/image/teacher.png'))
          data.avatar = require('@/assets/image/teacher.png')
        } else {
          commit('SET_AVATAR', require('@/assets/image/student.png'))
          data.avatar = require('@/assets/image/student.png')
        }
        // 避免字符串太长无法存储
        delete data.token
        saveCookie('info', JSON.stringify(data))
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        clearInfo()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

